package com.hupu.jrs.ui.userprofile

import com.hupu.jrs.injector.PerActivity
import javax.inject.Inject
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.functions.Func1

/**
 * Created by sll on 2016/3/11.
 */
@PerActivity
class UserProfilePresenter @Inject
constructor(private val mGameApi: GameApi, private val uid: String) : UserProfileContract.Presenter {

    private var mSubscription: Subscription? = null
    private var mUserProfileView: UserProfileContract.View? = null

    override fun receiveUserInfo() {
        mUserProfileView!!.showLoading()
        mSubscription = mGameApi.getUserInfo(uid).map(Func1<Any, Any> { userData ->
            userData?.result
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(Action1<Any> { userResult ->
            mUserProfileView!!.hideLoading()
            if (userResult != null) {
                mUserProfileView!!.renderUserData(userResult)
            } else {
                mUserProfileView!!.showError()
            }
        }, Action1<Throwable> {
            mUserProfileView!!.hideLoading()
            mUserProfileView!!.showError()
        })
    }

    fun attachView(view: UserProfileContract.View) {
        mUserProfileView = view
    }

    fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mUserProfileView = null
    }
}
